package com.example.browser;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class dialog_cv extends Activity {
    private ListView lv;
    private MyDatabaseHelper dbHelper;
    private String get_title;//暂存从数据库得到的title和url
    private String titler;//按值查找详细信息
    int id,get_id; //暂存从数据库得到的id
    private ArrayList arrayList=new ArrayList();
    private boolean if_exsit;
    private TextView clear,tip;
    private Button cancel;
    private static final String FILENAME="NGS";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_cv);
        getWindow().setGravity(Gravity.BOTTOM);//底部出现
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int displayheight = displayMetrics.heightPixels;//高度
        int displayWidth = displayMetrics.widthPixels;//宽度
//弹窗宽高
        getWindow().setLayout(displayWidth, (int) (displayheight*0.4));//设置弹窗宽高
        lv=(ListView)findViewById(R.id.cv_list);
        tip=(TextView)findViewById(R.id.tip);
        clear=(TextView)findViewById(R.id.clear) ;
        cancel=(Button)findViewById(R.id.cancel) ;
        intview();
        queryinfo();


    }

    private void intview() {

//点击函数：
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
                if (if_exsit) {
                    Intent intent = new Intent(dialog_cv.this, webview.class);//没有任何参数（意图），只是用来传递数据
                    intent.putExtra("searchText", share.getString("searchurl", "https://www.baidu.com/s?wd=")+query_by_id3(position));
                    startActivity(intent);
                    finish();
                }


            }
        });
        //长按选择删除
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                new AlertDialog.Builder(dialog_cv.this)
                        .setItems(new String[]{"删除","复制到手机剪切板"}, (dialog, which) -> {
                            switch (which) {
                                case 0:
                                    if (if_exsit)
                                        delete_dialog(position);
                                    break;
                                case 1:
                                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                                    ClipData mClipData = ClipData.newPlainText("Label",query_by_id3(position));
                                    cm.setPrimaryClip(mClipData);
                                    Toast.makeText(dialog_cv.this, "已复制到粘贴板", Toast.LENGTH_SHORT).show();
                                    break;

                            }
                        })
                        .show();

                return true;
            }
        });
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete_all_dialog();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               finish();

            }
        });
    }
    //全部删除对话框
    public void delete_all_dialog(){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定全部删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete_all();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //全部删除
    public void delete_all(){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from cvDB", null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete("cvDB","id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        //arrayList.clear();
        queryinfo();
    }
    public void delete_dialog(int position){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete(position);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    public void delete(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("cvDB","id=?",new String[] {String.valueOf(arrayList.get(position))});
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
       // arrayList.clear();
        queryinfo();


    }

    public String query_by_id3(int position) {
        dbHelper = new MyDatabaseHelper(this, "dmbrowser.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from cvDB", null);
        while (cursor.moveToNext()) {

            titler = cursor.getString(1);

            id = cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return titler;
    }
    public void queryinfo(){
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        arrayList.clear();
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        //查询语句也可以这样写
        Cursor cursor = db.query("cvDB", null, null, null, null, null, "id desc");        if (cursor != null && cursor.getCount() > 0) {
            if_exsit=true;
            lv.setVisibility(View.VISIBLE);
            tip.setVisibility(View.GONE);
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);

                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("search_pic",String.valueOf(R.drawable.search));
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.search_hiszujian,
                        new String[] {"title","search_pic"},
                        new int[] {R.id.search_histxt,R.id.search_icon});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exsit=false;
            lv.setVisibility(View.GONE);
            tip.setVisibility(View.VISIBLE);

        }

        cursor.close();
        db.close();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //finish();//点击窗口外部区域 弹窗消失
        return true;
    }
}